package com.gdth;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import com.gdth.utils.ImageUtil;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

/**
 * AsyncImageLoader
 * @author Arvin
 *
 */
public class AsyncImageLoader {
	private HashMap<String, SoftReference<Bitmap>> imageCache; 
	
    public AsyncImageLoader() {  
        imageCache = new HashMap<String, SoftReference<Bitmap>>();  
    }  
       
    public Bitmap loadDrawable(final String imageUrl, final ImageCallback imageCallback) {  
        if (imageCache.containsKey(imageUrl)) {  
            SoftReference<Bitmap> softReference = imageCache.get(imageUrl);  
            Bitmap drawable = softReference.get();  
            if (drawable != null) {  
                return drawable;
            }  
        }  
          
        final Handler mHandler = new Handler(new Handler.Callback() {

    		@Override
    		public boolean handleMessage(Message msg) {
    			imageCallback.imageLoaded((Drawable) msg.obj, imageUrl); 
                return false;
    		}
             
        });
        
        new Thread() {  
            @Override  
            public void run() {
            	Bitmap drawable = loadImageFromUrl(imageUrl);  
                imageCache.put(imageUrl, new SoftReference<Bitmap>(drawable));
                
                Message message = mHandler.obtainMessage(0, drawable);  
                mHandler.sendMessage(message);  
            }  
        }.start();  
        
        return null;  
    }
        
    /**
     * 加载图片
     * @param url
     * @return
     */
    public static Bitmap loadImageFromUrl(String url) {  
    	return ImageUtil.getBitmap(url);  
	}  
       
   public interface ImageCallback {  
        public void imageLoaded(Drawable imageDrawable, String imageUrl);  
          
    }  
}
